package com.library.service.Impl;

import com.library.constant.MessageConstant;
import com.library.dto.UserDTO;
import com.library.dto.UserLoginDTO;
import com.library.dto.UserPasswordDTO;
import com.library.entity.User;
import com.library.exception.AccountNotFoundException;
import com.library.exception.PasswordErrorException;
import com.library.mapper.UserMapper;
import com.library.service.UserService;
import com.library.utils.PwdUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    /**
     * 用户登录
     * @param userLoginDTO
     * @return
     */
    @Override
    public User login(UserLoginDTO userLoginDTO) {
        String username = userLoginDTO.getUsername();
        String password = userLoginDTO.getPassword();

        //根据用户名查询数据库中的数据
        User user = userMapper.getByUsername(username);

        if(user == null){
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        //密码比对
        boolean result = PwdUtil.decrypt(password, user.getPassword());
        if(!result) {
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        return user;
    }

    /**
     * 用户注册
     * @param userDTO
     */
    @Override
    public void register(UserDTO userDTO) {
        User user = new User();

        //对象属性拷贝
        BeanUtils.copyProperties(userDTO, user);

        //设置默认值,默认新增用户为普通用户
        user.setRole(0);

        //密码进行加盐加密
        String password = userDTO.getPassword();
        password = PwdUtil.encrypt(password);
        user.setPassword(password);

        userMapper.insert(user);

    }

    @Override
    public void update(UserDTO userDTO) {
        User user = new User();
        BeanUtils.copyProperties(userDTO, user);
        user.setPassword(null);
        userMapper.update(user);
    }

    @Override
    public void updatePassword(UserPasswordDTO userPasswordDTO) {
        //根据用户id查询用户数据
        User user = userMapper.getById(userPasswordDTO.getUserId());
       boolean result = PwdUtil.decrypt(userPasswordDTO.getOldPassword(), user.getPassword());
       if(!result){
           throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
       }
       user.setPassword(PwdUtil.encrypt(userPasswordDTO.getNewPassword()));
       userMapper.update(user);
    }

    @Override
    public User getUserByUsername(String username) {
        return userMapper.getByUsername(username);
    }


}
